# -*- codeing = utf-8 -*-
# @Time : 2022/8/6 0:04
# @Author : ZN
# @Email : 747723508@qq.com
# @File : serializers.py
# @Software: PyCharm
from django.contrib.auth.models import User
from rest_framework import serializers
from rest_framework.serializers import ModelSerializer

from .models import *
import re


class UserDetailSerializer(ModelSerializer):
    class Meta:
        model = UserDetail
        # fields = '__all__'
        exclude = ['is_delete']
        extra_kwargs = {
            'avatar': {'read_only': True},
            'user': {'required': False, 'write_only': True},
        }


class UserSerializer(ModelSerializer):
    userdetail = UserDetailSerializer(required=False,
                                      read_only=True)  # 序列化器嵌套UserDetailSerializer，使用UserDetail模型类小写定义。作用可以用user.detail,也可以用detail.user,获取到关联的表信息

    class Meta:
        model = User
        exclude = ['password', 'last_name', 'user_permissions', ]  # 定义网页使用UserSerializer序列化器的视图方法显示字段

        extra_kwargs = {
            'id': {'read_only': True},
            'last_login': {'read_only': True},
            'is_superuser': {'read_only': True},
            'is_staff': {'read_only': True},
            'is_active': {'read_only': True},
            'date_joined': {'read_only': True},
            'groups': {'read_only': True},
        }


class UpdatePasswordSerializer(serializers.Serializer):
    password = serializers.CharField(max_length=60, label='原密码')
    new_password = serializers.CharField(max_length=60, label='新密码')
    re_new_password = serializers.CharField(max_length=60, label='确认新密码')

    def validate(self, attrs):
        if attrs['new_password'] != attrs['re_new_password']:
            raise serializers.ValidationError('两次密码输入不同')
        return attrs


class AreaSerializer(ModelSerializer):
    class Meta:
        model = Area
        fields = ['id', 'name']


class ParentSerializer(ModelSerializer):  # parent是外键关联自身Area表，一对多查询
    area_set = AreaSerializer(many=True, read_only=True)  # 源模型类名小写_set会生成一个管理器 管理器可以查询源模型所有数据

    class Meta:
        model = Area
        fields = ['id', 'name', 'area_set']


class AddressSerializer(ModelSerializer):
    province_name = serializers.CharField(source='province.name', read_only=True)
    city_name = serializers.CharField(source='city.name', read_only=True)
    district_name = serializers.CharField(source='district.name', read_only=True)

    class Meta:
        model = Address
        exclude = ['is_delete','province','city','district']

    def validate_mobile(self, value):
        if not re.match(r'1[3-9]\d{9}$',value):
            raise serializers.ValidationError('手机号格式错误')
        return value

